﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Drawing.Printing;
using FlexCel.Core;
using System.Drawing.Drawing2D;
using FlexCel.XlsAdapter;
using System.IO;
using Report;


namespace MDIDemo.Modules
{
    public partial class PrintPreview : DevExpress.XtraEditors.XtraForm
    {
        ReportGenerator _rpGen = null;
        DataSet _ds = new DataSet();
        int idIn = 90;
        int idXls = 91;
        Dictionary<string, object> _valueList = new Dictionary<string, object>();
        void SetPermission()
        {
            if (this.Parent.Parent is frmMain)
            {
                frmMain main = (frmMain)this.Parent.Parent;
                btnPrint.Visible = frmMain.IsPermis(idIn, main.CurrentPermis.PERMISSION);
                btnExcel.Visible = frmMain.IsPermis(idXls, main.CurrentPermis.PERMISSION);
            }
        }
        public Dictionary<string, object> ValueList
        {
            get
            {
                return _valueList;
            }
            set { _valueList = value; }
        }
        public DataSet DataSource
        {
            get { return _ds; }
            set { _ds = value; }
        }
        string _reportCode = "";

        public string ReportCode
        {
            get { return _reportCode; }
            set { _reportCode = value; }
        }
        public PrintPreview()
        {
            InitializeComponent();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (!LoadPreferences()) return;
                if (!DoSetup(flexCelPrintDocument1)) return;
                flexCelPrintDocument1.Print();
                DialogResult = System.Windows.Forms.DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Lỗi in ấn");
            }
        }
        private bool LoadPreferences()
        {
            try
            {
                flexCelPrintDocument1.Workbook = flexCelImgExport1.Workbook;
                ExcelFile Xls = flexCelPrintDocument1.Workbook;
                Xls.PrintHeadings = false;
                Xls.PrintGridLines = false;
                //Xls.PrintPaperSize = TPaperSize.

                flexCelPrintDocument1.DefaultPageSettings.PaperSize = new PaperSize(Xls.PrintPaperDimensions.PaperName, Convert.ToInt32(Xls.PrintPaperDimensions.Width), Convert.ToInt32(Xls.PrintPaperDimensions.Height));
                //flexCelPrintDocument1.PrintPa
                flexCelPrintDocument1.DefaultPageSettings.Landscape = (Xls.PrintOptions & TPrintOptions.Orientation) == 0;
                return true;
            }
            catch (Exception ex) { throw ex; }
        }
        private bool DoSetup(PrintDocument doc)
        {
            printDialog1.Document = doc;
            printDialog1.PrinterSettings.DefaultPageSettings.PaperSize = doc.DefaultPageSettings.PaperSize;
            //printDialog1.PrinterSettings.
            bool Result = printDialog1.ShowDialog() == DialogResult.OK;
            //printDialog1.PrinterSettings.PaperSizes = doc.PrinterSettings.pga
            //Landscape.Checked = flexCelPrintDocument1.DefaultPageSettings.Landscape;
            return Result;
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            flexCelPreview1.StartPage = 1;
            UpdatePages();
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            flexCelPreview1.StartPage--; UpdatePages();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            flexCelPreview1.StartPage++; UpdatePages();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            flexCelPreview1.StartPage = flexCelPreview1.TotalPages; UpdatePages();
        }

        private void btnZoomOut_Click(object sender, EventArgs e)
        {
            flexCelPreview1.Zoom -= 0.1f;
            UpdateZoom();
        }

        private void btnZoomIn_Click(object sender, EventArgs e)
        {
            flexCelPreview1.Zoom += 0.1f;
            UpdateZoom();
        }

        private void edPage_Leave(object sender, EventArgs e)
        {
            ChangePages();
        }

        private void edPage_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                ChangePages();
            if (e.KeyChar == (char)27)
                UpdatePages();
        }
        private void ChangePages()
        {
            string s = edPage.Text.Trim();
            int pos = 0;
            while (pos < s.Length && s[pos] >= '0' && s[pos] <= '9') pos++;
            if (pos > 0)
            {
                int page = flexCelPreview1.StartPage;
                try
                {
                    page = Convert.ToInt32(s.Substring(0, pos));
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message, "Lỗi in ấn");
                }

                flexCelPreview1.StartPage = page;
            }
            UpdatePages();
        }
        private void UpdatePages()
        {
            edPage.Text = String.Format("{0} of {1}", flexCelPreview1.StartPage, flexCelPreview1.TotalPages);
        }

        private void edZoom_Enter(object sender, EventArgs e)
        {
            ChangeZoom();
        }

        private void edZoom_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                ChangeZoom();
            if (e.KeyChar == (char)27)
                UpdateZoom();
        }
        private void UpdateZoom()
        {
            edZoom.Text = String.Format("{0}%", (int)Math.Round(flexCelPreview1.Zoom * 100));
        }

        private void ChangeZoom()
        {
            string s = edZoom.Text.Trim();
            int pos = 0;
            while (pos < s.Length && s[pos] >= '0' && s[pos] <= '9') pos++;
            if (pos > 0)
            {
                int zoom = (int)Math.Round(flexCelPreview1.Zoom * 100);
                try
                {
                    zoom = Convert.ToInt32(s.Substring(0, pos));
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message, "Lỗi in ấn");
                }

                flexCelPreview1.Zoom = zoom / 100f;
            }
            UpdateZoom();
        }

        private void cbAntiAlias_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbAntiAlias.SelectedIndex)
            {
                case 1:
                    flexCelPreview1.SmoothingMode = SmoothingMode.HighQuality;
                    break;
                case 2:
                    flexCelPreview1.SmoothingMode = SmoothingMode.HighSpeed;
                    break;
                default:
                    flexCelPreview1.SmoothingMode = SmoothingMode.AntiAlias;
                    break;
            }

            if (flexCelImgExport1.Workbook != null) flexCelPreview1.InvalidatePreview();
        }

        private void PrintPreview_Load(object sender, EventArgs e)
        {
            SetPermission();
            _rpGen = new ReportGenerator(_ds, _reportCode, "", "", frmMain.ReportPath + "\\", frmMain.ReportOut + "\\", "");
            _rpGen.ValueList = _valueList;
            XlsFile xls = null;
            try
            {
                xls = new XlsFile();
                if (File.Exists(frmMain.ReportPath + "\\NODATA.xls"))
                    xls.Open(frmMain.ReportPath + "\\NODATA.xls");
                else
                {
                    if (File.Exists(frmMain.ReportPath + "\\NODATA.xls"))
                    {
                        File.Copy(frmMain.ReportPath + "\\NODATA.xls", frmMain.ReportPath + "\\NODATA.xls");
                        xls.Open(frmMain.ReportPath + "\\NODATA.xls");
                    }
                }

                //_rpGen.Name = txtdesr.Text;

                _rpGen.UserID = frmMain.__userID;
                ExcelFile _xlsFile = _rpGen.CreateReport();


                _xlsFile.Recalc();
                cbAntiAlias.SelectedIndex = 0;

                flexCelImgExport1.Workbook = _xlsFile;
                flexCelPreview1.InvalidatePreview();
                //      _xlsFile.Save(frmMain.ReportOut + "\\" + _reportCode + ".xls");
                ChangePages();
                UpdatePages();
                ChangeZoom();
                UpdateZoom();
            }
            catch (Exception ex)
            {
                string filename = String.Format("{0}\\{1}.template{2}", frmMain.ReportPath, _reportCode, ReportGenerator.Ext);
                flexCelImgExport1.Workbook = xls;
                flexCelPreview1.InvalidatePreview();
                XtraMessageBox.Show(ex.Message + "\nTemplate:" + filename, "Lỗi in ấn");
            }
        }

        private void btnDong_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            if (sfdExcel.ShowDialog() == DialogResult.OK)
            {
                ExcelFile xls = flexCelImgExport1.Workbook;
                xls.Save(sfdExcel.FileName);
                if (XtraMessageBox.Show("Bạn muốn mở file vừa tạo?", "Thông báo", MessageBoxButtons.OKCancel) == DialogResult.OK)
                    System.Diagnostics.Process.Start(sfdExcel.FileName);
                DialogResult = System.Windows.Forms.DialogResult.OK;
                Close();
            }
        }
    }
}